#include <iostream>
using std::cout;
using std::endl;

class Data
{
public:
    Data(){
        cout << "Data()" << endl;
    }

    Data(int x)
    :_data(x)
    {}
    
    int getData()const{
        return _data;
    }

    ~Data(){
        cout << "~Data()" << endl;
    }

private:
    int _data = 10;
};

class MidderLayer{
public:
    MidderLayer(Data* p)
    :_pdata(p)
    {
        cout << "MidderLayer(Data*)" << endl;
    }

    Data* operator->(){
        return _pdata;
    }

    Data & operator*(){
        return *_pdata;
    }

    ~MidderLayer(){
        cout << "~MidderLayer()" << endl;
        if(_pdata){
            delete _pdata;
            _pdata = nullptr;
        }
    }
private:
    Data* _pdata;
};

class ThirdLayout{
public:
    ThirdLayout(MidderLayer* pml)
    :_ml(pml)
    {
        cout << "MidderLayer(MidderLayer*)"<< endl;
    }

    ~ThirdLayout(){
        cout << "~ThirdLayout()"<< endl;
        if(_ml){
            delete _ml;
            _ml = nullptr;
        }
    }

    MidderLayer & operator->(){
        return *_ml;
    }
    
    Data & operator*(){
        return *(*_ml);
        //return (*_ml).operator*(); 
        //return *((*_ml)._pdata);
    }


private:
    MidderLayer* _ml;
};

void test0(){
    ThirdLayout tl(new MidderLayer(new Data));
    cout << (tl.operator->())->getData() << endl;
    cout << ((tl.operator->()).operator->())->getData() << endl;
    cout << tl->getData() << endl;


    cout << (*tl).getData() << endl;

}

int main(int argc, char * argv[])
{
    test0();
    return 0;
}


